package cn.example.util.toolkit;

import cn.example.util.ToolFactory;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;

/**
 * 图片操作工具类，目前用于验证码处理
 * <p/>
 * 2013-5-29 上午9:13:40
 *
 * @author huyang
 */
public class ImageUtil {

    private static class SingletonHolder {
        private static final ImageUtil INSTANCE = new ImageUtil();
    }

    private ImageUtil() {
    }

    public static ImageUtil getInstance() {
        return SingletonHolder.INSTANCE;
    }


    public BufferedImage createImage(String securityCode) {
        return createImage(securityCode, 15);
    }

    public BufferedImage createImage(String securityCode, int fSize) {
        int codeLength = securityCode.length();  // 验证码长度
        int fWidth = fSize + 2;  // 字体大小
        int width = codeLength * fWidth + 8;   // 图片宽度
        int height = fSize * 2 + 1;// 图片高度
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);   // 图片
        Graphics g = image.createGraphics();
        g.setColor(Color.WHITE); // 设置背景色
        g.fillRect(0, 0, width, height);// 填充背景
        g.setColor(Color.LIGHT_GRAY);   // 设置边框颜色
        g.setFont(new Font("Arial", Font.BOLD, height - 2));  // 边框字体样式
        g.drawRect(0, 0, width - 1, height - 1);  // 绘制边框
        Random rand = new Random();  // 绘制噪点
        RandomUtil randomUtil = ToolFactory.getRandomUtil();
        for (int i = 0; i < codeLength * 6; i++) {
            g.setColor(new Color(randomUtil.random(200, 245), randomUtil.random(200, 245), randomUtil.random(200, 245)));  // 设置噪点颜色
            int x = rand.nextInt(width);
            int y = rand.nextInt(height);
            g.drawRect(x, y, 2, 2);  // 绘制1*1大小的矩形
        }

        for (int i = 0; i < codeLength; i++) {// 绘制验证码
            g.setColor(new Color(randomUtil.random(5, 250), randomUtil.random(5, 250), randomUtil.random(5, 250)));   // 设置字体颜色和样式
            g.setFont(getRandomFont(fSize));
            g.drawString(String.valueOf(securityCode.charAt(i)), i * (fSize - 2) + 5,
                    height - randomUtil.random(5, 13));
        }

        g.dispose();// 关闭资源
        return image;
    }

    /**
     * 随机生成字体、文字大小
     *
     * @param fSize 字体大小
     * @return Font
     */
    private Font getRandomFont(int fSize) {
        String[] fonts = {"Georgia", "Verdana", "Arial", "Tahoma", "Time News Roman", "Courier New", "Arial Black", "Quantzite"};
        int fontIndex = (int) Math.round(Math.random() * (fonts.length - 1));
        int fontSize = (int) Math.round(Math.random() * 3 + fSize);
        return new Font(fonts[fontIndex], Font.PLAIN, fontSize);
    }


}
